const express = require('express');
const path = require('path');
const config = require('./config/index');
const log4js = require("log4js");
const createError = require('http-errors');
const cookieParser = require('cookie-parser');
log4js.configure({
    appenders: {
        cheese: {
            type: 'DateFile',
            filename: './log/access.log',
            pattern: '-yyyy-MM-dd.log',
            alwaysIncludePattern: true,
            category: 'access'
        }
    },
    categories: { default: { appenders: ["cheese"], level: "info" } }
});

const userRouter = require('./router/user');

const app = express();

// 处理静态资源
app.use(express.static(path.join(__dirname, 'static')));

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

// 告诉express能够解析 application/json类型的请求参数
app.use(express.json());
// 告诉express能够解析 表单类型的请求参数 application/x-www-form-urlencoded
app.use(express.urlencoded({extended: false}));
// 可以解析cookie
app.use(cookieParser());

// 服务器所处环境
console.log(process.env.NODE_ENV);

// 处理日志
app.use(log4js.connectLogger(log4js.getLogger('access'), {level: log4js.levels.INFO}));

app.get('/', (req, res, next) => {
    res.writeHead(200, {
        'Content-Type': 'text/plain; charset=utf-8;'
    })
    res.end('欢迎来到王者峡谷！')
})

// 使用用户路由
app.use('/api/user', userRouter);

// 错误处理，处理未匹配到的路由
app.use((req, res, next)=>{
    next(createError(404));
});

app.use((err, req, res, next)=>{
    console.log(err.status, err.message);
    res.json({
        code: err.status,
        msg: err.message
    });
});

app.listen(config.APP_PORT, () => {
    console.log(`服务器在${config.APP_HOST}:${config.APP_PORT}端口启动成功~`)
})